#pragma once

#include"Callback.h"
#include "noncopyable.h"
#include"InetAddress.h"
#include"Buffer.h"
#include"Timestamp.h"

#include <memory>
#include <string>
#include<atomic>

class Channel;
class EventLoop;
class Socket;

/*
TcpServer 通过Acceptor 获取连接 通过accept得到fd
打包成TcpConnection设置回调 ，回调给Channel ，把Channel注册到poller
poller监听到事件后，调用回调

*/

class TcpConnection : noncopyable, public std::enable_shared_from_this<TcpConnection>
{
public:
    TcpConnection(EventLoop* loop, const std::string & name, int sockfd, const InetAddress& localAddr, const InetAddress& peerAddr);
    ~TcpConnection();

    EventLoop* getLoop() const {return loop_;}
    const std::string& name() const {return name_;}
    const InetAddress& localAddress() const {return localAddr_;}
    const InetAddress& peerAddress() const {return peerAddr_;}

    bool connected() const {return state_ == kConnected;}

    //发送数据
    void send(const std::string& buf);
    //关闭连接
    void shutdown();

    void setConnectionCallback(const ConnectionCallback& cb){connectionCallback_ = cb;}
    void setMessageCallback(const MessageCallback& cb){messageCallback_ = cb;}
    void setWriteCompleteCallback(const WriteCompleteCallback& cb){writeCompleteCallback_ = cb;}
    void setHighWaterMarkCallback(const HighWaterMarkCallback& cb){highWaterMarkCallback_ = cb;}
    void setCloseCallback(const CloseCallback& cb){closeCallback_ = cb;}

    //连接建立
    void connectEstablished();
    //连接销毁
    void connectedDestroyed();



private:


    void handleRead(Timestamp receiveTime);
    void handleWrite();
    void handleClose();
    void handleError();

    

    void sendInLoop(const void* message, size_t len);
    void shutdownInLoop();

    enum StateE
    {
        kDisconnected,
        kConnecting,
        kConnected,
        kDisconnecting
    };
    void setState(StateE state){ state_ = state;}
    EventLoop *loop_; // subloop，tcpconnection都会交给subloop
    const std::string name_;
    std::atomic_int state_;
    bool reading_;

    //
    std::unique_ptr<Socket> socket_;
    std::unique_ptr<Channel> channel_;

    const InetAddress localAddr_;
    const InetAddress peerAddr_;

    ConnectionCallback connectionCallback_;//有新连接的callback
    MessageCallback messageCallback_;//有读写消息的callback
    WriteCompleteCallback writeCompleteCallback_;//消息发送完成的callback
    HighWaterMarkCallback highWaterMarkCallback_;
    CloseCallback closeCallback_;

    size_t highWaterMark_;
    Buffer inputBuffer_; //接收数据buffer
    Buffer outputBuffer_;//发送数据buffer

};